package osami.communication;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * TCPIPConnectionListener listens to incoming TCP/IP connections and
 * creates new connection objects for connecting clients
 * 
 * @author osami
 *
 */
public class TCPIPConnectionListener implements ConnectionListener
{
	private Activator iEngine;
	private CommServer iCommServer;
	private ServerSocket iProviderSocket;
	private Thread iListenerThread = null;
	
	public static final int PORT = 6744;	// 6744 = OSGI

	/**
	 * Creates a new instance of TCPIPConnectionListener
	 * 
	 * @param aEngine
	 * @param aCommServer
	 */
	public TCPIPConnectionListener( Activator aEngine, CommServer aCommServer )
	{
		iEngine = aEngine;
		iCommServer = aCommServer;
		
		// create and start a thread in which the listener runs
		iListenerThread = new Thread( this );
		iListenerThread.start();
	}
	
	
	/**
	 * Creates a server socket and starts to listen to incoming connections.
	 * 
	 */
	public void run()
	{
		boolean running = true;

		try
		{
			// create a server socket
			System.out.println( "TCPIPConnectionListener.run: Creating the server socket..." );
			iProviderSocket = new ServerSocket( TCPIPConnectionListener.PORT, 10 );	
		}
		catch( IOException aException )
		{
			System.out.println( "TCPIPConnectionListener.run: Could not create listener: " + aException.getMessage() );
			return;
//			exception.printStackTrace();
		}

		while( running && !iProviderSocket.isClosed() )
		{
			try
			{
				// wait for a connection
				Socket connection = iProviderSocket.accept();

				// create a new client connection object
				if ( connection != null )
				{
					System.out.println( "TCPIPConnectionListener.run: A client from " + connection.getInetAddress().getHostAddress() + " has connected!" );
					Connection client = new TCPIPConnection( iEngine, iCommServer, connection );
					
					iCommServer.addClient( client );
				}
			}
			catch( IOException aException )
			{
				System.out.println( "TCPIPConnectionListener.run: socket closed: " + aException.getMessage() );
//				exception.printStackTrace();
			}
		}
	}

	
	/**
	 * Closes server socket.
	 * 
	 * @throws IOException
	 */
	public void closeConnection() 
	{
		try
		{
			if ( iProviderSocket != null )
				iProviderSocket.close();

			iListenerThread.interrupt();
		}
		catch ( IOException aException )
		{
			// TODO Auto-generated catch block
			aException.printStackTrace();
		}
	}
}
